package com.chen.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //首页所有人可以访问，功能页只有对应有全向的人才能访问
        //链式编程 http认证请求  添加一个地址 选择所有人
        //请求授权的规则     //只有vip*下的才可以访问
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

        //没有权限默认会跳到登录页面   定制跳转页面   自定义参数
        http.formLogin().loginPage("/toLogin").usernameParameter("user").passwordParameter("pwd").loginProcessingUrl("/login");

        //开启注销功能 跳转到首页  参数介绍 移除所有的cookie  清空所有的session(会话)
       // http.logout().deleteCookies("remove").invalidateHttpSession(true);

        //默认注销  去指定页面
        http.logout().logoutSuccessUrl("/");

        //关闭跨站脚本请求攻击的功能
        http.csrf().disable();

        //开启记住我功能  自定义接受前端参数  cookie默认保存2周
        http.rememberMe().rememberMeParameter("remember");
    }


    //认证
    //密码未加密  反编译为class文件
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //内存中认证
     auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
             .withUser("chenchao").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
             .and()
             .withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
             .and()
             .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }
}
